

package jetbrains.buildServer.server.rest.data.util;

import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import org.jetbrains.annotations.NotNull;

/**
 * Set-based duplicate checker, useful for checking duplicates using some key, not the item itself, e.g. checking VcsModifications by version.
 */
public class KeyDuplicateChecker<ITEM, KEY> implements DuplicateChecker<ITEM> {
  private final Function<ITEM, KEY> myKeyExtractor;
  private final Set<KEY> mySeenKeys = new HashSet<>();

  public KeyDuplicateChecker(@NotNull Function<ITEM, KEY> keyExtractor) {
    myKeyExtractor = keyExtractor;
  }

  @Override
  public boolean checkDuplicateAndRemember(@NotNull ITEM item) {
    return !mySeenKeys.add(myKeyExtractor.apply(item));
  }
}